var  CryptoJS = require("crypto-js");

// SHA256
function sha256(data){
  return CryptoJS.SHA256(data).toString()
}
// MD5
function md5(data){
  return CryptoJS.MD5(data).toString()
}
// aes加密
export function aesEncrypt(data,secretKey){
   let key = CryptoJS.enc.Utf8.parse(secretKey);
     let srcs = CryptoJS.enc.Utf8.parse(data);
    let encrypted = CryptoJS.AES.encrypt(data, key, { mode:CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
    return encrypted.toString();
}
//aes解密
export function aesDecrypt(data,secretKey){
  const key = CryptoJS.enc.Utf8.parse(secretKey);
  let decrypt = CryptoJS.AES.decrypt(data, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
  return decrypt.toString(CryptoJS.enc.Utf8);
}

function getDateTimeToString(){
  const date_ = new Date()
  let year = date_.getFullYear()
  let month = date_.getMonth() + 1
  let day = date_.getDate()
  if (month < 10){
    month = '0' + month
  } 
  if (day < 10){
    day = '0' + day
  } 
  let hours = date_.getHours()
  let mins = date_.getMinutes()
  let secs = date_.getSeconds()
  let msecs = date_.getMilliseconds()
  if (hours < 10){
    hours = '0' + hours
  } 
  if (mins < 10){
    mins = '0' + mins
  } 
  if (secs < 10){
    secs = '0' + secs
  }
  if (msecs < 10){
    secs = '0' + msecs
  } 
  return year + '' + month + '' + day + '' + hours + '' + mins + '' + secs
}

function getNonce(){
  return Math.random().toString(36).substring(2)
}

/**
 * 接口参数签名
 * @param {*} params 请求配置
 */
export function sign(params, appId, appSecret, signType,method){
  // 获取到秒级的时间戳,与后端对应
  let data = {
    APPID: appId,
    TIMESTAMP: getDateTimeToString(),
    SIGNTYPE: signType,
    NONCE: getNonce()
  }
let singData={};
  const _singKey = 'SIGN'
  const _secretKey = 'SECRETKEY'
  let keys = []
  if (method === 'get') {
    // url参数签名
    singData['securityParam'] = params = params ? aesEncrypt(params,appSecret) : aesEncrypt({},appSecret)
    keys = Object.keys(singData)
  } else {
    // request body参数的内容
    singData['securityParam'] = params = params ? aesEncrypt(params,appSecret) : aesEncrypt({},appSecret)
    keys = Object.keys(singData)
  }
  // 排序
  const skeys = keys.sort()
  let str = ''
  skeys.filter(k => {
    return k !== _singKey && k !== _secretKey
  }).map(k => {
    const v = singData[k]
    if (v || v === 0) {
      // 参数值为空，则不参与签名
      str = str + k + '=' + v + '&'
    }
  })
  str = str + _secretKey + '=' + appSecret+data.TIMESTAMP+data.NONCE
  let sign = ''
  if (data.SIGNTYPE === 'MD5') {
    sign = md5(str).toUpperCase()
  }
  if (data.SIGNTYPE === 'SHA256') {
    sign = sha256(str).toUpperCase()
  }
  let heade  = data;
  
  if (method === 'get') {
    heade[_singKey] = sign
  } else {
    heade[_singKey] = sign
  }
  let result = {
    headers:heade,
    params:singData
  }
  return result
}
